import math
import os
import xml.etree.cElementTree as xml

cls_num = {'have_mask':0,'no_mask':1}
imga_path = 'E:/python file/yolo_advance/JPEGImages'
file_class = os.listdir(imga_path)
xml_path = 'E:/python file/yolo_advance/Annotations'
xml_class = os.listdir(xml_path)
def read_file(imag,path):
    file_path = os.path.join(imag,path)
    name = os.listdir(file_path)
    return name
class_name = []
class_path = []
for name in file_class:
    names = read_file(imga_path,name)
    class_name.append(names)
for i,names in enumerate(class_name) :
    for name in names:
        image = os.path.join(imga_path,file_class[i],name)
        class_path.append(image)
xml_name = []
xml_filepath = []
for name in xml_class:
    names = read_file(xml_path,name)
    xml_name.append(names)
for i,names in enumerate(xml_name) :
    for name in names:
        image = os.path.join(xml_path,xml_class[i],name)
        xml_filepath.append(image)
with open('E:/python file/yolo_advance/date.txt','a') as f:
    for path  in xml_filepath[::12]:
        tree = xml.parse(path)
        root = tree.getroot()
        data = []
        boxes = root.findall('object/bndbox')
        names = root.findall('object/name')
        floder = root.find('folder')
        filename = root.find('filename')
        data.append(floder.text)
        data.append(filename.text)
        for name,box in zip(names,boxes):
            class_index = cls_num[name.text]
            data.append(class_index)
            cx,cy,w,h = math.floor((int(box[0].text)+int(box[2].text))/2),math.floor((int(box[1].text)+int(box[3].text))/2),int(box[2].text)-int(box[0].text),int(box[3].text)-int(box[1].text)
            data.append(cx)
            data.append(cy)
            data.append(w)
            data.append(h)
        text= ''
        for i in data:
            text = text + str(i) + ' '
        text +='\n' 
        f.write(text)
f.close()